import { Injectable, NestMiddleware } from '@nestjs/common';
import { Request, Response, NextFunction } from 'express';
import prismaClient from '@/config/prismaClient';
import { throwHttpException1 } from '@/utils/nesjUtils';

// 校验入参
@Injectable()
class CheckParamIsEmptyMiddleware implements NestMiddleware {
  use(req: Request, res: Response, next: NextFunction) {
    // 1、校验整体参数是否传递
    if (Object.keys(req.body).length == 0) {
      throwHttpException1({
        state: '0',
        msg: '请检查参数是否正确！',
        data: '',
      });
    }
    const requiredFields = [
      { name: 'ID', field: 'ID' },
      { name: '密码', field: 'Password' },
    ];
    const errFields = requiredFields.filter((f) => {
      if (!!!req.body[f.field]) {
        return f;
      }
    });

    if (errFields.length != 0) {
      throwHttpException1({
        state: '0',
        msg: `请检查参数是否正确！必填项: ${errFields.map((f) => f.name).join('、')}`,
        data: '',
      });
    }

    next();
  }
}

@Injectable()
class CheckIDIsExistMiddleware implements NestMiddleware {
  async use(req: Request, res: Response, next: NextFunction) {
    // 1、校验整体参数是否传递
    const body = req.body as { ID: string };
    const baseUserList = await prismaClient.base_user.findMany({
      where: {
        ID: body.ID,
        IsDel: '0',
      },
    });

    if (baseUserList.length == 0) {
      throwHttpException1({
        state: '0',
        msg: `请检查参数是否正确！以下ID未找到: ${body.ID}`,
        data: '',
      });
    }

    next();
  }
}

export default {
  CheckParamIsEmptyMiddleware,
  CheckIDIsExistMiddleware,
};
